  <script lang="ts">
    import { onMount } from 'svelte';
    import L from 'leaflet';
    import 'leaflet/dist/leaflet.css';
    import 'leaflet.markercluster/dist/MarkerCluster.css';
    import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
    import 'leaflet-curve'; // 引入 leaflet-curve 插件
    import vietnam from '../data/vietnam.json';

    let mapContainer: HTMLElement;

    onMount(async () => {
      mapContainer.style.backgroundColor = 'transparent'; // 设置背景透明

      const map = L.map(mapContainer, {
        center: [16.8471, 106.5068], // Centered around Da Nang
        zoom: 6,
        backgroundColor: 'transparent',
        scrollWheelZoom: false // 关闭鼠标滚轮缩放
      });

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19,
        opacity: 0.0, // 设置地图瓦片为全透明
        className: 'map-tiles'
      }).addTo(map);

      // 添加越南边界
      L.geoJSON(vietnam, {
        style: {
          color: '#3B82F6',
          weight: 2,
          opacity: 1,
          fillColor: '#3B82F6',
          fillOpacity: 0.2
        },
        onEachFeature: (feature, layer) => {
          layer.on({
            mouseover: (e) => {
              const layer = e.target;
              layer.setStyle({
                weight: 3,
                color: '#60A5FA',
                fillOpacity: 0.4
              });
            },
            mouseout: (e) => {
              const layer = e.target;
              layer.setStyle({
                color: '#3B82F6',
                weight: 2,
                opacity: 0.8,
                fillColor: '#3B82F6',
                fillOpacity: 0.2
              });
            }
          });
        }
      }).addTo(map);

      // Updated mock locations with 10 cities
      const mockLocations = [
  { lat: 21.0285, lng: 105.8542, name: 'Hanoi<br/>（河内）' },
  { lat: 16.0678, lng: 108.2208, name: 'Da Nang<br/>（岘港）' },
  { lat: 10.7627, lng: 106.6602, name: 'Ho Chi Minh City<br/>（胡志明市）' },
  { lat: 20.8605, lng: 106.7822, name: 'Hai Phong<br/>（海防）' },
  { lat: 21.1861, lng: 106.1008, name: 'Bắc Ninh<br/>（北宁）' },
  { lat: 21.7333, lng: 107.7700, name: 'Móng Cái<br/>（芒街）' }
];

      // 自定义图标样式
      // const customIcon = L.icon({
      //   iconAnchor: [32, 32], // 图标锚点
      // });

      // 智能标签位置偏移算法
      function calculateLabelOffset(index: number, totalCount: number, baseRadius = 25) {
        const angles = [0, 45, -45, 90, -90, 135, -135, 180]; // 8个方向
        const angle = angles[index % angles.length];
        const radius = baseRadius + Math.floor(index / angles.length) * 15; // 如果超过8个，增加半径
        
        const radian = (angle * Math.PI) / 180;
        const offsetX = Math.cos(radian) * radius;
        const offsetY = Math.sin(radian) * radius;
        
        return { x: offsetX, y: offsetY };
      }

      // 添加点位到地图
      mockLocations.forEach((location, index) => {
        const offset = calculateLabelOffset(index, mockLocations.length);
        
        // 创建点位标记（无文字）
        L.marker([location.lat, location.lng], {
          icon: L.divIcon({
            className: 'ripple-marker',
            html: `<div class="rippleItem"> 
            <div class="ripple"></div>
            </div>
          `,
          })
        }).addTo(map);

        // 创建独立的文字标签（带偏移）
        L.marker([location.lat, location.lng], {
          icon: L.divIcon({
            className: 'label-marker',
            html: `<div class="city-label" style="transform: translate(${offset.x}px, ${offset.y}px)">
              ${location.name}
            </div>`,
            iconSize: [100, 30],
            iconAnchor: [60, 15]
          })
        }).addTo(map);
      });

      // 创建弧形轨迹线的函数
      function createCurvedPath(start: [number, number], end: [number, number], curvature = 0.3) {
        const points = [];
        const numPoints = 50; // 生成50个点来形成平滑弧线
        
        // 计算中点和弯曲控制点
        const midLat = (start[0] + end[0]) / 2;
        const midLng = (start[1] + end[1]) / 2;
        
        // 计算垂直于起点-终点连线的方向，用于创建弧形
        const deltaLat = end[0] - start[0];
        const deltaLng = end[1] - start[1];
        
        // 弧形控制点（在中点基础上垂直偏移）
        const controlLat = midLat - deltaLng * curvature;
        const controlLng = midLng + deltaLat * curvature;
        
        // 使用二次贝塞尔曲线生成路径点
        for (let i = 0; i <= numPoints; i++) {
          const t = i / numPoints;
          const oneMinusT = 1 - t;
          
          const lat = oneMinusT * oneMinusT * start[0] + 
                     2 * oneMinusT * t * controlLat + 
                     t * t * end[0];
          const lng = oneMinusT * oneMinusT * start[1] + 
                     2 * oneMinusT * t * controlLng + 
                     t * t * end[1];
          
          points.push([lat, lng]);
        }
        
        return points;
      }

      // 为所有点位之间创建连线
      const connectionLines: any[] = [];
      
      // 遍历所有点位，为每对点创建连线
      for (let i = 0; i < mockLocations.length; i++) {
        for (let j = i + 1; j < mockLocations.length; j++) {
          const startPoint: [number, number] = [mockLocations[i].lat, mockLocations[i].lng];
          const endPoint: [number, number] = [mockLocations[j].lat, mockLocations[j].lng];
          
          // 根据距离调整弧度，距离越远弧度越大
          const distance = Math.sqrt(
            Math.pow(endPoint[0] - startPoint[0], 2) + 
            Math.pow(endPoint[1] - startPoint[1], 2)
          );
          const curvature = Math.min(distance * 0.02, 0.3); // 限制最大弧度
          
          const curvedPath = createCurvedPath(startPoint, endPoint, curvature);
          
                     const connectionLine = L.polyline(curvedPath, {
             color: '#3B82F6', // 蓝色
             weight: 1.5,      // 1.5px宽度
             opacity: 0.7,     // 透明度
             smoothFactor: 3,  // 平滑因子
             dashArray: '8, 12', // 虚线模式：8px实线，12px空隙
             className: 'animated-dash-line' // 添加CSS类名用于动画
           }).addTo(map);
          
          connectionLines.push(connectionLine);
        }
      }




      // 轨迹动画功能（暂时注释，因为需要自定义图标）
      // let currentIndex = 0;
      // const animateTrajectory = () => {
      //   if (currentIndex < mockLocations.length - 1) {
      //     const start = mockLocations[currentIndex];
      //     const end = mockLocations[currentIndex + 1];
      //     const marker = L.marker([start.lat, start.lng], { icon: customIcon }).addTo(map);
      //     const latlngs = [start, end];
      //     const line = L.polyline(latlngs, { color: 'blue', weight: 2 }).addTo(map);

      //     // Simple animation logic
      //     let step = 0;
      //     const steps = 100;
      //     const interval = setInterval(() => {
      //       step++;
      //       const lat = start.lat + (end.lat - start.lat) * (step / steps);
      //       const lng = start.lng + (end.lng - start.lng) * (step / steps);
      //       marker.setLatLng([lat, lng]);

      //       if (step === steps) {
      //         clearInterval(interval);
      //         map.removeLayer(marker);
      //         map.removeLayer(line);
      //         currentIndex++;
      //         animateTrajectory();
      //       }
      //     }, 50);
      //   }
      // };

      // animateTrajectory();
    });
  </script>

  <div bind:this={mapContainer} class="map-container"></div>

  <style scoped>
    .map-container {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      background-color: transparent; /* 设置背景透明 */
    }

    /* 地图瓦片透明度 */
    :global(.map-tiles) {
      /* 移除滤镜 */
    }

    /* 自定义弹出框样式 */
    :global(.leaflet-popup-content-wrapper) {
      background-color: rgb(2,17,32);
      color: white;
    }

    :global(.leaflet-popup-tip) {
      background-color: rgb(2,17,32);
    }

    /* 自定义控件样式 */
    :global(.leaflet-control-zoom a) {
      background-color: rgb(2,17,32) !important;
      color: white !important;
      border-color: rgba(255,255,255,0.2) !important;
    }

    :global(.leaflet-control-attribution) {
      background-color: rgb(2,17,32) !important;
      color: rgba(255,255,255,0.7) !important;
    }

    /* 确保地图容器背景色 */
    :global(.leaflet-container) {
      background-color: transparent !important; /* 设置背景透明 */
    }

    /* 虚线动画效果 */
    @keyframes dash-flow {
      0% {
        stroke-dashoffset: 0;
      }
      100% {
        stroke-dashoffset: 20;
      }
    }

    :global(.animated-dash-line) {
      stroke-dasharray: 8, 12 !important;
      stroke-dashoffset: 0;
      animation: dash-flow 3s linear infinite;
    }
    :global(.ripple-marker) {
      position: relative;
      color: #fff;
      /* background-color: #3B82F6; */
    }

    :global(.label-marker) {
      pointer-events: none; /* 避免标签干扰地图交互 */
    }

    :global(.city-label) {
      font-size: 12px;
      line-height: 1.2;
      color: #fff;
      text-shadow: 1px 1px 2px rgba(0,0,0,0.8);
      background: rgba(0,0,0,0.6);
      padding: 4px 8px;
      border-radius: 4px;
      white-space: nowrap;
      text-align: center;
      border: 1px solid rgba(59, 130, 246, 0.5);
      backdrop-filter: blur(2px);
    }
    
    :global { 
      /* .ripple {
      position: absolute;
      border: 2px solid #3B82F6;
      border-radius: 50%;
      background-color: #fff;
      animation: ripple-animation 3s infinite;
      opacity: 0;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    } */

    .rippleItem {
      position: absolute;
      width: 16px;
      height: 16px;
      margin-top: -8px;
      margin-left: -8px;
    }
  

    .ripple {
      width: 16px;
      height: 16px;
      animation-delay: 0s;
    }



    @keyframes ripple-animation {
      0% {
        transform: scale(0.5);
        opacity: 1;
      }
      /* 50% {
        transform: scale(1.2);
        opacity: 0;
      } */
      100% {
        transform: scale(1.2);
        opacity: 0;
      }
    }
  }
  </style>